package com.hz.ruoyimqttconsume.utils;

import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author 侯文波
 * @date 2025/3/12 19:13
 * @description: 缓存工具类
 */
@Component
public class LatestDataCache {
    private static final int MAX_CACHE_SIZE = 100; // 最大缓存大小
    private final ConcurrentMap<String, Object> pestCache = new ConcurrentHashMap<>();
    private final ConcurrentMap<String, Object> soilCache = new ConcurrentHashMap<>();
    private final ConcurrentMap<String, Object> envCache = new ConcurrentHashMap<>();


    /**
     * 限制缓存大小
     * @param cache
     */
    private void limitCacheSize(ConcurrentMap<String, Object> cache) {
        if (cache.size() > MAX_CACHE_SIZE) {
            // 移除最早的元素
            cache.entrySet()
                    .stream()
                    .min(Map.Entry.comparingByKey())
                    .ifPresent(entry -> cache.remove(entry.getKey()));
        }
    }

    public void updatePestData(Object data) {
        pestCache.put(LocalDateTime.now().toString(), data);
        limitCacheSize(pestCache);
    }

    public void updateSoilData(Object data) {
        soilCache.put(LocalDateTime.now().toString(), data);
        limitCacheSize(soilCache);
    }

    public void updateEnvData(Object data) {
        envCache.put(LocalDateTime.now().toString(), data);
        limitCacheSize(envCache);
    }

    public Object getLatestPestData() {
        return getLatestEntry(pestCache);
    }

    public Object getLatestSoilData() {
        return getLatestEntry(soilCache);
    }

    public Object getLatestEnvData() {
        return getLatestEntry(envCache);
    }

    private Object getLatestEntry(ConcurrentMap<String, Object> cache) {
        if (cache.isEmpty()) {
            return null;
        }
        Map.Entry<String, Object> latestEntry = cache.entrySet()
                .stream()
                .max(Map.Entry.comparingByKey())
                .orElse(null);
        if (latestEntry != null) {
            cache.remove(latestEntry.getKey());
            return latestEntry.getValue();
        }
        return null;
    }

} 
